package com.justgame.project.service.system.controller;


import com.justgame.mq.client.constant.SystemQueueConstant;
import com.justgame.mq.client.service.RabbitMqSendService;
import com.justgame.project.base.annotation.ProtectAccess;
import com.justgame.project.cloud.common.constant.Const;
import com.justgame.project.cloud.common.constant.Regex;
import com.justgame.project.cloud.common.constant.Result;
import com.justgame.project.cloud.common.enums.TimeEnum;
import com.justgame.project.cloud.common.util.Encryption;
import com.justgame.project.cloud.common.util.HttpUtil;
import com.justgame.project.cloud.common.util.RedisUtils;
import com.justgame.project.cloud.common.util.ShiroUtils;
import com.justgame.project.service.system.dto.SysUserInfoDTO;
import com.justgame.project.service.system.service.ISysUserInfoService;
import com.wf.captcha.SpecCaptcha;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.core.MediaType;
import java.io.IOException;
import java.util.Map;

@Slf4j
@RequestMapping("/sys")
@RestController
@RequiredArgsConstructor
public class SysController {
    private final RedisUtils redisUtils;
    private final ISysUserInfoService sysUserInfoService;
    private final RabbitMqSendService rabbitMqSendService;

    private final static String B_VIDEOS_LIST_URL = "http://api.bilibili.com/x/web-interface/search/all/v2";

    @GetMapping("test")
    public Result<?> test(){
        return Result.ok("success");
    }

    /**
     * 邮箱变更
     *
     * @param dto
     * @return
     */
    @PutMapping("/change-email")
    public Result<Object> changeEmail(@RequestBody SysUserInfoDTO dto) {
        return Result.ok(/*sysUserInfoService.changeEmail(dto)*/);
    }

    /**
     * 生成验证码
     *
     * @param response
     */
    @GetMapping("/verification")
    public void buildVerificationCode(HttpServletRequest request, HttpServletResponse response) {
        try {
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            ServletOutputStream outputStream = response.getOutputStream();
            SpecCaptcha captcha = new SpecCaptcha(100, 40, 5);
            String code = captcha.text().toLowerCase();
            StringBuffer sb = Encryption.PasswordMD5(code);
            String md5code = String.valueOf(sb);
            ShiroUtils.setSessionAttribute(Const.KEY_VERIFICATION_CODE_2WEB, md5code);
            redisUtils.set(request.getSession().getId(), md5code, TimeEnum.MINUTE.getTime(15) / 1000);
            captcha.out(outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * B站获取视频列表接口
     *
     * @return
     */
    @GetMapping("/third-party-api/b")
    public Result<Object> bilibiliVideoList(@RequestParam Map<String, Object> params) {
        String url = String.format("%s%s", B_VIDEOS_LIST_URL, HttpUtil.buildUrlParams(params));
        return Result.ok(HttpUtil.get(url));
    }

    /**
     * 给邮箱发送验证码
     *
     * @param mail
     * @return
     */
    @GetMapping("/email/send-validation")
    @ProtectAccess(value = 3L)
    public Result<?> email(String mail) {
        /* 检查字段 */
        Assert.hasLength(mail,"邮箱地址不能为空！");
        Assert.isTrue(Regex.isEmail(mail),"邮箱格式不正确！");
        Assert.isTrue(sysUserInfoService.countByEmailIs(mail) == 0,"该邮箱已被使用，无法绑定！");
        Assert.isTrue(!redisUtils.isExists(Const.EMAIL_VALIDATION_TIMEOUT + mail),"请勿频繁发送邮箱验证码！");
        /* 判断发送邮件次数 */
        int hasSendCount = Integer.parseInt(redisUtils.get(Const.EMAIL_VALIDATION_COUNT + mail, "0"));
        Assert.isTrue(hasSendCount < Const.EMAIL_VALIDATION_MAX_COUNT,"您发送验证码次数已达到当日上限，请次日再试！");
        rabbitMqSendService.sendMsg(SystemQueueConstant.SYSTEM_EMAIL_AUTH_QUEUE,mail);
        return Result.ok("发送成功！");
    }

}
